package com.atguigu.realtime.app.dwm;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONAware;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.realtime.app.BaseAppV1;
import com.atguigu.realtime.common.Constant;
import com.atguigu.realtime.util.FlinkSinkUtil;
import com.atguigu.realtime.util.KKutil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.logging.SimpleFormatter;

public class DwmUvApp extends BaseAppV1 {
    public static void main(String[] args) {
        new DwmUvApp().init(3001,1,"DwmUvApp","DwmUvApp", Constant.TOPIC_DWD_PAGE);
    }
    @Override
    protected void run(StreamExecutionEnvironment env,
                       DataStreamSource<String> stream) {
        stream
                .map(JSON::parseObject)
                // 添加水印
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy.<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                       .withTimestampAssigner((page,ts)-> page.getLong("ts")) //事件事件
                )

               .keyBy(page-> page.getJSONObject("common").getString("mid"))
                .window(TumblingEventTimeWindows.of(Time.seconds(5))) // 滑动窗口 事件 ，大小为5s

                .process(new ProcessWindowFunction<JSONObject, JSONObject, String, TimeWindow>() {

                    private SimpleDateFormat sdf;
                    private ValueState<String> dateState;

                    @Override
                    public void open(Configuration parameters) throws Exception { // 存储状态，为了区分跨天
                        sdf = new SimpleDateFormat("yyyy-MM-dd");
                        // 2021-12-28
                        dateState = getRuntimeContext().getState(new ValueStateDescriptor<String>("dateState", String.class));
                    }

                    @Override
                    public void process(String key,
                                        Context ctx,
                                        Iterable<JSONObject> elements,
                                        Collector<JSONObject> out) throws Exception {
                        // 考虑跨天，当跨天的时候，清空状态dateState
                        String yesterday = dateState.value();
                        String today = sdf.format(ctx.window().getStart());
                        if (!today.equals(yesterday)) {
                            dateState.clear();

                        }

                        if (dateState.value() == null) {
                            List<JSONObject> list = KKutil.toList(elements);
                            JSONObject min = Collections.min(list, Comparator.comparing(o -> o.getLong("ts")));
                            out.collect(min);
                            dateState.update(sdf.format(min.getLong("ts")));
                        }
                    }
                })

                .map(JSONAware::toJSONString)// 把JSON类型转换成string类型

                .addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWM_UV));
    }
}
/*
* dwd_page dwd_start dwd_display
*   消费的topic:
*   选择启动日志，计算的uv值会偏小，对网页，微信等非app启动的无法统计，只有app启动的时候才有启动日志
*
*   选择页面日志：
*
* */